<template>
  <div class="page-bg">
    <div class="content-box">
      <div class="min-h-screen bg-gray-100">
        <div class="container mx-auto px-4 py-8 h-screen flex flex-col">
          <!-- 首页 -->
          <HomePage v-if="!showTest && !showResult && !showArticleResult && !showArticleResultBtn"
            @start-standard-test="startStandardTest" @start-article-test="startArticleTest" class="flex-grow" />

          <!-- 标准测试页面 -->
          <div v-else-if="!showResult && !showArticleResult && !showArticleResultBtn"
            class="bg-white rounded-lg shadow-lg p-8 flex-grow flex flex-col">
            <div class="text-center mb-8">
              <p style="text-align: center; font-size: 2rem; font-weight: 600; margin: -0.5rem auto -2rem auto;">
                个人词汇量测试
              </p>
              <p style="text-align: center; font-size: 3rem; font-weight: 600; margin: 2.5rem auto 1rem auto;">{{
                currentWord.word }}
              </p>
            </div>

            <div class="justify-center items-center">

              <!-- <h1 class="text-5xl font-bold text-gray-800 mb-12">{{ currentWord.word }}</h1> -->
              <div class="g-progress" :style="`--progress: ${(currentWordIndex + 1) / 50 * 100}%`"></div>
              <p class="text-xl text-gray-700">{{ currentWordIndex + 1 }}/50</p>
              <div class="judge-button" style="display: flex; justify-content: center; gap: 1.5rem;">
                <el-button type="success" size="large" @click="handleWordResponse(true)" :disabled="isProcessing"
                  class="text-lg px-8">
                  认识
                </el-button>
                <el-button type="danger" size="large" @click="handleWordResponse(false)" :disabled="isProcessing"
                  class="text-lg px-8">
                  不认识
                </el-button>
              </div>
            </div>
          </div>

          <!-- 结果页面 -->
          <div v-else-if="showResult" class="bg-white rounded-lg shadow-lg p-8 flex-grow flex flex-col">
            <div class="flex-grow flex flex-col justify-center items-center">
              <p style="text-align: center; font-size: 2rem; font-weight: 600; margin: -0.5rem auto 0rem auto;">
                个人词汇量估计结果：
              </p>
              <p>
                <a style="font-size: 2rem; font-weight: 600;">约为</a>
                <a style="font-size: 3rem; font-weight: 600; margin-bottom: 1rem;">
                  <span class="text-blue-600 font-bold">{{ estimatedVocabulary }}</span>
                </a>
                <a style="font-size: 2rem; font-weight: 600;">个单词</a>
              </p>

              <el-button type="primary" @click="resetTest" size="large" class="test-button text-lg px-8">
                重新测试
              </el-button>
            </div>
          </div>

          <!-- 文章检测结果页面 -->
          <ArticleVocabResult v-else-if="showArticleResult" :vocab="estimatedVocabulary" @reset="resetArticleTest"
            class="bg-white rounded-lg shadow-lg p-8 flex-grow" :confidence="confidence" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed } from 'vue'
  import HomePage from './components/HomePage.vue'
  import ArticleVocabResult from './components/ArticleVocabResult.vue'
  import { ElMessage } from 'element-plus'

  // API基础URL
  const API_BASE_URL = 'http://localhost:8081/api'

  // 状态变量
  const showTest = ref(false)
  const showResult = ref(false)
  const showArticleResult = ref(false)
  const showArticleResultBtn = ref(false)
  const estimatedVocabulary = ref(0)
  const currentWordIndex = ref(0)
  const isProcessing = ref(false)
  const testedWords = ref([])
  const currentWord = ref(null)
  const currentAbilityLevel = ref(4) // 初始能力水平
  const confidence = ref(0.5) // 添加可信度状态变量

  // 开始标准测试
  const startStandardTest = async () => {
    try {
      showTest.value = true
      currentWordIndex.value = 0
      testedWords.value = []
      currentAbilityLevel.value = 4

      // 获取第一个单词
      await getNextWord()
    } catch (error) {
      ElMessage.error('启动测试失败')
      console.error(error)
    }
  }

  // 获取下一个单词
  const getNextWord = async () => {
    try {
      const usedWords = testedWords.value.map(w => w.word)
      const response = await fetch(`${API_BASE_URL}/vocabulary/next-word?abilityLevel=${currentAbilityLevel.value}&usedWords=${usedWords.join(',')}`)

      if (response.ok) {
        const wordData = await response.json()
        currentWord.value = {
          word: wordData.word,
          difficultyLevel: wordData.difficultyLevel
        }
      } else {
        ElMessage.error('获取单词失败')
      }
    } catch (error) {
      ElMessage.error('获取单词失败')
      console.error(error)
    }
  }

  // 处理用户对单词的响应
  const handleWordResponse = async (isKnown) => {
    if (isProcessing.value) return // 防止重复点击

    isProcessing.value = true

    try {
      // 记录当前单词的测试结果
      testedWords.value.push({
        word: currentWord.value.word,
        difficultyLevel: currentWord.value.difficultyLevel,
        known: isKnown
      })

      // 更新当前单词索引
      currentWordIndex.value++

      // 动态调整能力水平
      if (isKnown) {
        currentAbilityLevel.value = Math.min(8, currentAbilityLevel.value + 1)
      } else {
        currentAbilityLevel.value = Math.max(1, currentAbilityLevel.value - 1)
      }

      // 检查是否完成测试
      if (testedWords.value.length >= 50) {
        await calculateVocabulary()
        showResult.value = true
        isProcessing.value = false
        return
      }

      // 获取下一个单词
      await getNextWord()
    } catch (error) {
      ElMessage.error('处理响应失败')
      console.error(error)
    } finally {
      isProcessing.value = false
    }
  }

  // 计算词汇量
  const calculateVocabulary = async () => {
    try {
      const response = await fetch(`${API_BASE_URL}/vocabulary/estimate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(testedWords.value)
      })

      if (response.ok) {
        const result = await response.json()
        estimatedVocabulary.value = result.estimatedSize
      } else {
        ElMessage.error('计算词汇量失败')
      }
    } catch (error) {
      ElMessage.error('计算词汇量失败')
      console.error(error)
    }
  }

  // 重置测试
  const resetTest = () => {
    // 重置所有状态变量
    showTest.value = false
    showResult.value = false
    showArticleResult.value = false
    showArticleResultBtn.value = false
    estimatedVocabulary.value = 0
    currentWordIndex.value = 0
    testedWords.value = []
    isProcessing.value = false
    currentWord.value = null
    currentAbilityLevel.value = 4
  }

  // 开始文章测试
  const startArticleTest = async (file) => {
    try {
      const formData = new FormData()
      formData.append('file', file)

      const response = await fetch(`${API_BASE_URL}/article/estimate`, {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const result = await response.json()
        estimatedVocabulary.value = result.estimatedVocab
        confidence.value = result.confidence || 0.5 // 获取可信度信息
        showTest.value = false
        showResult.value = false
        showArticleResult.value = true
      } else {
        ElMessage.error('文章分析失败')
      }
    } catch (error) {
      ElMessage.error('处理文章时出错')
      console.error(error)
    }
  }

  // 重新检测（返回首页）
  const resetArticleTest = () => {
    showArticleResult.value = false
    estimatedVocabulary.value = 0
    confidence.value = 0.5 // 重置可信度
  }
</script>